import React, { useRef, useState } from "react"
import { useFrame } from "@react-three/fiber"
import * as THREE from "three"
import { GlowingTrail } from "./GlowingTrail"

function GlowingBall() {
  const meshRef = useRef()
  const [trailPoints, setTrailPoints] = useState([])

  useFrame(({ clock }) => {
    const t = clock.getElapsedTime()
    const x = Math.sin(t * 2) * 4
    const y = Math.abs(Math.sin(t * 4)) * 2

    meshRef.current.position.set(x, y, 0)

    // 每帧记录位置（最多保留 N 个点）
    setTrailPoints((prev) => {
      const next = [...prev, [x, y, 0]]
      return next.length > 40 ? next.slice(-40) : next
    })
  })

  return (
    <>
      <mesh ref={meshRef}>
        <sphereGeometry args={[0.3, 32, 32]} />
        <meshBasicMaterial color="#00ffff" />
      </mesh>

      <GlowingTrail positionBuffer={trailPoints} />
    </>
  )
}

export default GlowingBall
